package com.beijing.demo.find;

import java.util.Arrays;

/**
 * 曹旭
 * 2025/4/23
 * 实现二分查找
 */
public class FindNumber {
    public static void main(String[] args) {
        System.out.println("test start~~");
        int testTime = 1000000;
        int len = 100;
        int value = 300;
        for (int i = 0; i < testTime; i++) {
            int[] ranArray = getRanArray(len, value);
            Arrays.sort(ranArray);
            int num = getRanValue(value);
            boolean isFind = isFind(ranArray, num);
            boolean isBinaryFind = isBinaryFind(ranArray,num);
            if(isFind != isBinaryFind){
                System.out.println("fucking fuck ~~");
                break;
            }
        }
        System.out.println("test end~~");
    }

    public static int[] getRanArray(int len,int value){
        int arrLen = (int)(Math.random() * (len + 1)); // [0,len]
        int[] arrs = new int[arrLen];
        for (int i = 0; i < arrs.length; i++) {
            arrs[i] = getRanValue(value); // [-value,value];
        }
        return arrs;
    }

    /**
     * 生成随机数
     * 范围[-value,value]
     * @return
     */
    public static int getRanValue(int value){
        return (int) (Math.random() * (value + 1)) - (int) (Math.random() * (value + 1));
    }

    /**
     * 暴力解法,用于对数器
     * @param arrs
     * @param num
     * @return
     */
    public static boolean isFind(int[] arrs,int num){
        if(arrs == null || arrs.length == 0){
            return false;
        }
        for (int i = 0; i < arrs.length; i++) {
            if(arrs[i] == num){
                return true;
            }
        }
        return false;
    }

    /**
     * 二分查找
     * @param arrs
     * @param num
     * @return
     */
    public static boolean isBinaryFind(int[] arrs,int num){
        if(arrs == null || arrs.length == 0){
            return false;
        }
        int l=0,r=arrs.length - 1;
        while(l <= r){
            int mid = l + ((r - l) >> 1);
            if(arrs[mid] < num){
                l = mid + 1;
            }else if (arrs[mid] > num){
                r = mid - 1;
            }else {
                return true;
            }
        }
        return false;
    }
}
